package com.sxtyxt.util;

import java.lang.ref.SoftReference;
import java.util.LinkedHashMap;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.util.Log;

/**
  2012-11-25
 */
public class ImageCache {
	
	private ImageCache(){}
	
	private static final String TAG="ImageCache";

	private static final int hardCachedSize = 8*1024*1024; 

	private static final LruCache<String, Bitmap> bitmapCache = new LruCache<String, Bitmap>(hardCachedSize){ 
		@Override 
		public int sizeOf(String key, Bitmap value){ 
			return value.getRowBytes() * value.getHeight(); 
		} 

		@Override 
		protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue){ 
			Log.v(TAG, "hard cache is full , push to soft cache"); 
			softBitmapCache.put(key, new SoftReference<Bitmap>(oldValue));
		} 
	}; 

	private static final int SOFT_CACHE_CAPACITY = 40; 
	private final static LinkedHashMap<String, SoftReference<Bitmap>> softBitmapCache = 
			new LinkedHashMap<String, SoftReference<Bitmap>>(SOFT_CACHE_CAPACITY, 0.75f, true){ 
		/**
		 * 
		 */
		private static final long serialVersionUID = -7624689207450857755L;

		@Override 
		public SoftReference<Bitmap> put(String key, SoftReference<Bitmap> value){ 
			return super.put(key, value); 
		}

		protected boolean removeEldestEntry(java.util.Map.Entry<String,java.lang.ref.SoftReference<Bitmap>> eldest) {
			if(size() > SOFT_CACHE_CAPACITY){ 
				Log.v(TAG, "Soft Reference limit , purge one"); 
				return true; 
			} 
			return false;
		};


	}; 

	public static  boolean putBitmap(String key, Bitmap bitmap){
		if(bitmap != null){ 
			synchronized(bitmapCache){ 
				bitmapCache.put(key, bitmap); 
			} 
			return true; 
		} 
		return false; 
	} 

	public static Bitmap getBitmap(String key){ 
		synchronized(bitmapCache){ 
			final Bitmap bitmap = bitmapCache.get(key); 
			if(bitmap != null) 
				return bitmap; 
		} 

		synchronized(softBitmapCache){ 
			SoftReference<Bitmap> bitmapReference = softBitmapCache.get(key); 
			if(bitmapReference != null){ 
				final Bitmap bitmap2 = bitmapReference.get(); 
				if(bitmap2 != null) 
					return bitmap2; 
				else{ 
					softBitmapCache.remove(key);
				} 
			} 
		} 
		return null; 
	}


	
	
}
